<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\OriginRobotSpinConfig;
use think\admin\Controller;
use think\facade\Db;
use ZipArchive;

/**
 * 超管系统-Spin测试
 * Class Banner
 * @package app\airobot\controller
 */
class TestSpin extends Controller
{
    private $table = 'robot_spin_config';
    public $commonLogic;

    /**
     * Spin测试
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = 'Spin测试';
        $query = $this->_query($this->table);
        $where = [];
        $query->where($where);
        $query->order('id desc')->page();
    }

    protected function _index_page_filter(array &$data)
    {
        try {
            $this->commonLogic = new CommonLogic();
            $boxIds = [];
            $forgeIds = [];
            foreach ($data as $vo) {
                if ($vo['spin_type'] == 1) {
                    $boxIds[] = $vo['box_id'];
                } else {
                    $forgeIds[] = $vo['forge_id'];
                }
            }
            // 查询Box
            $boxModel = new \app\airobot\model\RobotBox();
            $boxList = $boxModel->queryList([], ['field' => 'id', 'data' => $boxIds], [], [], [], "", $field = "*", $order = "");
            $boxListMap = array_column($boxList, null, 'id');

            // 查询forge
            $forgeModel = new \app\airobot\model\RobotForge();
            $forgeList = $forgeModel->queryList([], ['field' => 'id', 'data' => $forgeIds], [], [], [], "", $field = "*", $order = "");

            // 查询frogs的商品
            $productIds = [];
            foreach ($forgeList as $vo) {
                $productIds[] = $vo['product_id'];
            }
            $productModel = new \app\airobot\model\RobotProduct();
            $productList = $productModel->queryList([], ['field' => 'id', 'data' => $productIds], [], [], [], "", $field = "*", $order = "");
            $productListMap = array_column($productList, null, 'id');
            // forgeId和商品映射
            $forgeProductListMap = [];
            foreach ($forgeList as $vo) {
                $forgeProductListMap[$vo['id']] = $productListMap[$vo['product_id']];
            }

            foreach ($data as &$vo) {
                $vo['compensation_probability'] = "0%";
                if ($vo['total_spin_amount'] != 0) {
                    $vo['compensation_probability'] = number_format($vo['total_product_amount'] / $vo['total_spin_amount'] * 100, 2) . "%";
                }
                $vo['total_spin_amount'] = $this->commonLogic->DealAmount($vo['total_spin_amount']);
                $vo['total_product_amount'] = $this->commonLogic->DealAmount($vo['total_product_amount']);
                $vo['box_name'] = isset($boxListMap[$vo['box_id']]) ? $boxListMap[$vo['box_id']]['name'] : '';
                $vo['forge_name'] = isset($forgeProductListMap[$vo['forge_id']]) ? $forgeProductListMap[$vo['forge_id']]['name'] : '';
                $vo['times'] = $this->commonLogic->DealAmount($vo['times']);
                $vo['crt_complete_spin_times'] = $this->commonLogic->DealAmount($vo['crt_complete_spin_times']);
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }

    /**
     * 创建盲盒任务
     * @auth true
     */
    public function addbox()
    {
        if ($this->request->isPost()) {
            try {
                Db::startTrans();
                $data = $this->request->post();

                // 参数校验
                if (!is_numeric($data["times"]) || $data["times"] <= 0) {
                    $this->error("spin次数错误");
                }
                if (!is_numeric($data["box_id"]) || $data["box_id"] <= 0) {
                    $this->error("box_id错误");
                }
                if (!is_numeric($data["test_rtp"]) || $data["test_rtp"] <= 0) {
                    $this->error("测试赔率错误");
                }
                $robotBoxModel = new \app\airobot\model\RobotBox();
                $findBox = $robotBoxModel->queryInfo(['id' => $data["box_id"]]);
                if (empty($findBox) || $findBox['id'] != $data["box_id"]) {
                    $this->error("未找到盲盒ID");
                }

                // 创建任务
                $robotSpinConfigModel = new \app\airobot\model\RobotSpinConfig();
                $robotSpinConfigInfo = $robotSpinConfigModel->queryInfoByOrder([], "*", "batch_number desc");
                $maxBatchNumber = 1;
                if (!empty($robotSpinConfigInfo) && isset($robotSpinConfigInfo["batch_number"])) {
                    $maxBatchNumber = $robotSpinConfigInfo["batch_number"] + 1;
                }

                // 创建任务配置
                $createData = [];
                $createData["table_index"] = 1;
                $createData["run_type"] = $data["run_type"];
                $createData["run_user_id"] = 16;
                $createData["batch_number"] = $maxBatchNumber;
                $createData["spin_type"] = 1;
                $createData["test_rtp"] = $data["test_rtp"];
                $createData["times"] = $data["times"];
                $createData["box_id"] = $data["box_id"];
                $createData["forge_id"] = 0;
                $createData["total_spin_amount"] = 0;
                $createData["total_product_amount"] = 0;
                $createData["total_user_value"] = 0;
                $createData["product_win_times_json"] = "";
                $createData["use_time_seconds"] = "";
                $createData["crt_complete_spin_times"] = "0";
                $createData["status"] = 1;
                Db::table("robot_spin_config")->insert($createData);

                // 创建任务数据（box）
                $findBox['batch_number'] = $maxBatchNumber;
                $findBox['box_id'] = $findBox["id"];
                unset($findBox['id']);
                Db::table("robot_box_task")->insert($findBox);

                // 创建任务数据（user_rtp）
                $robotBoxRtpModel = new \app\airobot\model\RobotBoxRtp();
                $robotBoxRtpList = $robotBoxRtpModel->queryList([], [], [], [], [], "", $field = "*", $order = "");
                $batchCreateRtp = [];
                foreach ($robotBoxRtpList as $vo) {
                    $vo['rtp_id'] = $vo['id'];
                    $vo['batch_number'] = $maxBatchNumber;
                    unset($vo['id']);
                    $batchCreateRtp[] = $vo;
                }
                Db::table("robot_box_rtp_task")->insertAll($batchCreateRtp);

                // 创建任务数据（products）
                $robotProductModel = new \app\airobot\model\RobotProduct();
                $robotProductList = $robotProductModel->queryList([], [], [], [], [], "", $field = "*", $order = "");
                $batchCreateProduct = [];
                foreach ($robotProductList as $vo) {
                    $vo['batch_number'] = $maxBatchNumber;
                    $vo['product_id'] = $vo['id'];
                    unset($vo['id']);
                    $batchCreateProduct[] = $vo;
                }
                Db::table("robot_product_task")->insertAll($batchCreateProduct);

                // 如果一切正常，提交事务
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                error_log(var_export($exception->getMessage(), true) . "\n", 3, "/tmp/qp.log");
                $this->error($exception->getMessage());
            }

            $this->success("保存成功！");
        } else {
            OriginRobotSpinConfig::mForm('formbox');
        }
    }

    /**
     * 创建Forge任务
     * @auth true
     */
    public function addforge()
    {
        if ($this->request->isPost()) {
            try {
                // 开启事务
                Db::startTrans();

                $data = $this->request->post();

                // 参数校验
                if (!is_numeric($data["times"]) || $data["times"] <= 0) {
                    $this->error("spin次数错误");
                }
                if (!is_numeric($data["test_rtp"]) || $data["test_rtp"] <= 0) {
                    $this->error("测试赔率错误");
                }
                if ($data["forge_probability"] <= 0 || $data["forge_probability"] > 1) {
                    $this->error("默认概率错误");
                }
                if ($data["forge_user_chose_probability"] <= 0 || $data["forge_user_chose_probability"] > 1) {
                    $this->error("用户选择概率错误");
                }

                // 创建任务
                $robotSpinConfigModel = new \app\airobot\model\RobotSpinConfig();
                $robotSpinConfigInfo = $robotSpinConfigModel->queryInfoByOrder([], "*", "batch_number desc");
                $maxBatchNumber = 1;
                if (!empty($robotSpinConfigInfo) && isset($robotSpinConfigInfo["batch_number"])) {
                    $maxBatchNumber = $robotSpinConfigInfo["batch_number"] + 1;
                }

                // 创建任务
                $createData = [];
                $createData["table_index"] = 1;
                $createData["run_type"] = $data["run_type"];
                $createData["run_user_id"] = 16;
                $createData["batch_number"] = $maxBatchNumber;
                $createData["spin_type"] = 2;
                $createData["test_rtp"] = $data["test_rtp"];
                $createData["times"] = $data["times"];
                $createData["box_id"] = 0;
                $createData["forge_id"] = 1;
                $createData["forge_probability"] = $data["forge_probability"];
                $createData["forge_user_chose_probability"] = $data["forge_user_chose_probability"];
                $createData["total_spin_amount"] = 0;
                $createData["total_product_amount"] = 0;
                $createData["total_user_value"] = 0;
                $createData["product_win_times_json"] = "";
                $createData["use_time_seconds"] = "";
                $createData["crt_complete_spin_times"] = "0";
                $createData["config_file"] = "";
                $createData["status"] = 1;
                Db::table("robot_spin_config")->insert($createData);


                // 创建任务数据（user_rtp）
                $robotForgeRtpModel = new \app\airobot\model\RobotForgeRtp();
                $robotForgeRtpList = $robotForgeRtpModel->queryList([], [], [], [], [], "", $field = "*", $order = "");
                $batchCreateRtp = [];
                foreach ($robotForgeRtpList as $vo) {
                    $vo['rtp_id'] = $vo['id'];
                    $vo['batch_number'] = $maxBatchNumber;
                    unset($vo['id']);
                    $batchCreateRtp[] = $vo;
                }
                Db::table("robot_forge_rtp_task")->insertAll($batchCreateRtp);

                // 如果一切正常，提交事务
                Db::commit();
            } catch (\Exception $exception) {
                Db::rollback();
                error_log(var_export($exception->getMessage(), true) . "\n", 3, "/tmp/qp.log");
                $this->error($exception->getMessage());
            }


            $this->success("保存成功！");
        } else {
            OriginRobotSpinConfig::mForm('formforge');
        }
    }

    /**
     * 查看结果
     * @auth true
     */
    public function queryresult()
    {
        $robotSpinConfigModel = new \app\airobot\model\RobotSpinConfig();
        $vo = $robotSpinConfigModel->queryInfo(["id" => $_GET["id"]]);
        if ($vo['product_win_times_json'] == "") {
            $this->success("未执行完成！");
        }

        // 将 JSON 字符串解析为 PHP 对象或数组
        $paramsJson = json_decode($vo['product_win_times_json'], true);
        ksort($paramsJson);
        $formattedJsonString = json_encode($paramsJson, JSON_PRETTY_PRINT);
        if ($vo['spin_type'] == 1) {
            $paramsJson2 = [];
            foreach ($paramsJson as $k => $v) {
                $paramsJson2["product-id: " . $k] = $v;
            }
            $formattedJsonString = json_encode($paramsJson2, JSON_PRETTY_PRINT);
        }
        $vo['product_win_times_json'] = $formattedJsonString;

        $this->vo = $vo;
        OriginRobotSpinConfig::mForm('result');
    }

}